export async function handleStream(streamType, videoElement, streamRef, peerConnectionRef, isStreamingRef, endpointUrl) {
  try {
    if (streamType === 'video' && videoElement) {
      videoElement.value.srcObject = streamRef.value;
    }

    // 创建 RTCPeerConnection
    peerConnectionRef.value = new RTCPeerConnection();

    // 添加音视频轨道
    streamRef.value.getTracks().forEach(track => peerConnectionRef.value.addTrack(track, streamRef.value));

    // 创建 SDP Offer
    const offer = await peerConnectionRef.value.createOffer();
    await peerConnectionRef.value.setLocalDescription(offer);

    // 发送 WHIP 请求
    const response = await fetch(endpointUrl, {
      method: 'POST',
      body: offer.sdp,
      headers: { 'Content-Type': 'application/sdp' },
    });

    if (!response.ok) {
      throw new Error(`服务器返回错误: ${response.status} ${response.statusText}`);
    }

    // 检查响应体是否为空
    const responseBody = await response.text();
    if (!responseBody) {
      throw new Error('服务器返回空响应');
    }

    // 解析 SDP Answer
    const answer = { type: 'answer', sdp: responseBody };
    await peerConnectionRef.value.setRemoteDescription(answer);

    isStreamingRef.value = true;
    console.log('WHIP 推流成功！');
    return '';
  } catch (error) {
    console.error('推流失败:', error);
    return `推流失败: ${error.message}`;
  }
}

export function stopStream(streamRef, peerConnectionRef, isStreamingRef, otherStreamRef, videoElement) {
  if (streamRef.value) {
    streamRef.value.getTracks().forEach(track => track.stop());
    streamRef.value = null;
  }
  if (peerConnectionRef.value) {
    peerConnectionRef.value.close();
    peerConnectionRef.value = null;
  }
  isStreamingRef.value = false;
  if (videoElement && !otherStreamRef?.value) {
    videoElement.value.srcObject = null;
  }
  console.log('推流已停止');
}
